package com.shxc.smarttrade.old.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.UserInfoBean;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/11/3.
 */

public class PersonInfoActivity extends BaseActivity {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_telephone)
    TextView tvTelephone;
    @BindView(R.id.rb_man)
    RadioButton rbMan;
    @BindView(R.id.rb_woman)
    RadioButton rbWoman;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;

    private String sexOld = "0";//0：男  1：女
    private String nickOld = "";//性别
    private String sexNew = "0";//0：男  1：女
    private String nickNew = "";//性别

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    UserInfoBean.DataBean userInfoBean = (UserInfoBean.DataBean) msg.obj;
                    etName.setText(nickOld = userInfoBean.getNick());
                    sexOld = String.valueOf(userInfoBean.getSex());
                    tvTelephone.setText(userInfoBean.getTelphone());
                    if (userInfoBean.getSex() == 0)
                        rbMan.setChecked(true);
                    else
                        rbWoman.setChecked(true);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        initView();
        initListener();
        initData();
    }


    private void initView() {
        tvCenter.setText("个人信息设置");
        tvRight.setText("完成");
        tvRight.setTextColor(getResources().getColor(R.color.blue));
    }

    private void initListener() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_man:
                        sexNew = "0";
                        break;
                    case R.id.rb_woman:
                        sexNew = "1";
                        break;
                }
            }
        });

        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nickNew = etName.getText().toString().trim();
                if (nickNew.length() > 10) {
                    showToast("昵称太长 换个试试");
                    return;
                }
                if (TextUtils.isEmpty(nickNew)) {
                    showToast("昵称不可为空");
                    return;
                }


                if (nickNew.equals(nickOld) && sexNew.equals(sexOld))
                    finish();
                else
                    changeUserInfo();
            }
        });

    }

    private void initData() {
        getUserInfo();
    }

    @OnClick(R.id.rl_left)
    public void onViewClicked() {
        finish();
    }


    private void getUserInfo() {
        showShortDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userIdss);
        map.put("accessToken", accessTokenss);
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.PERSON_INFO_ACTIVITY_SHOWUSERINFO, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast("网络异常");
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Gson gson = new Gson();
                    UserInfoBean ub = gson.fromJson(response, UserInfoBean.class);
                    if (ub.getErr_code().equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        msg.obj = ub.getData();
                        handler.sendMessage(msg);
                    } else {
                        showToast(ub.getErr_msg());
                    }


                }
                dismissShortDialog();

            }
        });
    }

    private void changeUserInfo() {
        //对昵称进行校验
        showShortDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userIdss);
        map.put("accessToken", accessTokenss);
        map.put("nick", nickNew);
        map.put("sex", sexNew);
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.PERSON_INFO_ACTIVITY_EDIT_USERINFO, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast("网络异常");
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {

                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
                        showToast("修改成功");
                        EventBus.getDefault().post(new EventDatas(EventContents.PERSON_INFO_CHANGE_INFO, null));
                        finish();
                    } else {
                        showToast(errMsg);
                    }

                }
                dismissShortDialog();
            }
        });

    }
}
